package http.executor;

import http.annotation.ExceptionHandlerMethodResolver;
import http.mapping.HandlerMethod;
import http.mapping.InvocableHandlerMethod;
import http.thread.ExecutorFactor;
import http.util.ApplicationContextUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class Executor {

    static {
//       CachedThreadPool； 线程池为无限大，当执行第二个任务时第一个任务已经完成，会复用执行第一个任务的线程，而不用每次新建线程。
        ExecutorService pool = Executors.newSingleThreadExecutor();
        pool.execute(new Runnable() {
            @Override
            public void run() {
                 exec();
            }
        });

    }

    private static LinkedBlockingQueue<Task> messageQueue = new LinkedBlockingQueue<>();



    public static boolean put(String id,HandlerMethod handle){
        if(handle == null){
            return false;
        }
        try {
            messageQueue.put(new Task(handle,id));
            return true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static void exec()  {
        while (true){
            Task task=null;
            try {
                task=messageQueue.take();
                ExecutorFactor.exec(InvocableHandlerMethod.getInstance(),task);
            } catch (Exception e) {
//                1,查询用户是否有定制的的异常处理
//                2，有则调用
//                3，否则使用默认异常处理
                ExceptionHandlerMethodResolver resolver = ApplicationContextUtil.getBean(ExceptionHandlerMethodResolver.class);
                resolver.resolve(e,task.getId());

                e.printStackTrace();
            }
        }
    }
}
